﻿using System;
using System.Configuration;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Timers;

namespace Stock
{
    class Program
    {
        private static Timer stockTimer;
        private static string stockList;
        private static int inTimer = 0;
        static IStock stock = new SinaStock();

        static void Main(string[] args)
        {
            ShowShares();
        }

        /// <summary>
        /// 显示股票信息
        /// </summary>
        public static void ShowShares()
        {
            Console.WindowWidth = 80;
            Console.WindowHeight = 40;
            int interval = 5000;//默认值为5000ms
            int black_theme = 0;

            try
            {
                interval = int.Parse(GetConfig("interval").ToString()) * 1000;
                black_theme = int.Parse(GetConfig("black_theme").ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine("参数有误，请检查配置文件.");
                return;
            }

            if (black_theme == 0)
            {
                Console.BackgroundColor = ConsoleColor.White;
                Console.ForegroundColor = ConsoleColor.Gray;
            }

            string path = AppDomain.CurrentDomain.BaseDirectory + "\\shares.txt";

            if (!File.Exists(path))
            {
                Console.WriteLine("参数有误，请检查配置文件");
                return;
            }

            GetStockList(path);
            var d = stockList;
            //首次手动调用timer事件
            StockTimer_Elapsed(null, null);
            stockTimer = new Timer();
            stockTimer.Elapsed += StockTimer_Elapsed;
            stockTimer.Interval = interval;
            stockTimer.Start();
            Console.ReadKey();
        }

        private static void StockTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            //多线程环境下防止Timer重入
            if (System.Threading.Interlocked.Exchange(ref inTimer, 1) == 0)
            {
                Console.Clear();
                stock.PrintStock(stockList);
                System.Threading.Interlocked.Exchange(ref inTimer, 0);
            }
        }

        private static object GetConfig(string key)
        {
            return ConfigurationManager.AppSettings[key];
        }
        /// <summary>
        /// 获取股票列表
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetStockList(string path)
        {
            //股票代码集合，多个股票代码之间以‘，’分割
            using (StreamReader sr = new StreamReader(path, Encoding.Default))
            {
                string line;
                string[] sh = GetConfig("sh").ToString().Split(new char[] { ',' },
                    StringSplitOptions.RemoveEmptyEntries);
                string[] sz = GetConfig("sz").ToString().Split(new char[] { ',' },
                    StringSplitOptions.RemoveEmptyEntries);

                while ((line = sr.ReadLine()) != null)
                {
                    //如果股票代码前有--，则隐藏该股票，不显示
                    if (line.Contains("--"))
                    {
                        continue;
                    }

                    //处理股票代码:
                    if (!line.StartsWith("s"))
                    {
                        line = line.Substring(0, 6);
                        line = ProcessLine(line, sh, "sh");
                        line = ProcessLine(line, sz, "sz");
                    }
                    else
                    {
                        line = line.Substring(0, 8);
                    } 

                    stockList += line + ",";
                }
            }

            return stockList.Remove(stockList.Length - 1);

            string ProcessLine(string line, string[] sources, string prefix)
            {
                foreach (var item in sources)
                {
                    if (line.StartsWith(item))
                    {
                        line = $"{prefix}{line}";
                        break;
                    }
                }

                return line;
            }
        }
    }
}
